import React, { Component } from 'react';
import router from 'umi/router';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Steps, Button, Anchor, Affix, Row, Col, Modal, Spin, message } from 'antd';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '@/utils/utils.less';
import BasicInfo from './BasicInfo';
import ChargeInfo from './ChargeInfo';
import InsAccuInfo from './InsAccuInfo';
import ContInfo from './ContInfo';

const { Step } = Steps;
const { Link } = Anchor;
const { confirm } = Modal;

@connect(({ addinfo, publicdata, loading }) => ({
  addinfo,
  dictCode: publicdata.dictCode,
  loading: loading.models.addinfo,
  submitLoading:
    loading.effects['publicdata/fetchDictCode'] ||
    loading.effects['addinfo/submit'] ||
    loading.effects['addinfo/submitRepeat'],
}))
@Form.create({
  onFieldsChange(props, changedFields) {
    if (changedFields.requestInsAndAccuDto) {
      props.dispatch({
        type: 'addinfo/updateInsAccuData',
        payload: changedFields.requestInsAndAccuDto,
      });
    }
    if (changedFields.empLaborContDto) {
      props.dispatch({
        type: 'addinfo/updateContData',
        payload: changedFields.empLaborContDto,
      });
    }
    if (changedFields.requestAddBaseDto) {
      props.dispatch({
        type: 'addinfo/updateChargeData',
        payload: changedFields.requestAddBaseDto,
      });
    }
  },
  mapPropsToFields(props) {
    let requestInsAndAccuDto = {};
    Object.entries(props.addinfo.requestInsAndAccuDto).forEach(([key, value]) => {
      requestInsAndAccuDto = {
        ...requestInsAndAccuDto,
        [`requestInsAndAccuDto.${key}`]: Form.createFormField({
          ...props.addinfo.formRedux.requestInsAndAccuDto[key],
          value,
        }),
      };
    });
    Object.entries(props.addinfo.requestAddBaseDto).forEach(([key, value]) => {
      if (key === 'requestPdInfo') {
        value.forEach((item, index) => {
          requestInsAndAccuDto = {
            ...requestInsAndAccuDto,
            [`requestAddBaseDto.requestPdInfo[${index}][cityId]`]: Form.createFormField({
              ...(props.addinfo.formRedux.requestAddBaseDto.formReduxRequestPdInfo[index]
                ? props.addinfo.formRedux.requestAddBaseDto.formReduxRequestPdInfo[index].cityId
                : {}),
              value: item.cityId,
            }),
            [`requestAddBaseDto.requestPdInfo[${index}][execType]`]: Form.createFormField({
              ...(props.addinfo.formRedux.requestAddBaseDto.formReduxRequestPdInfo[index]
                ? props.addinfo.formRedux.requestAddBaseDto.formReduxRequestPdInfo[index].execType
                : {}),
              value: item.execType,
            }),
            [`requestAddBaseDto.requestPdInfo[${index}][startDate]`]: Form.createFormField({
              ...(props.addinfo.formRedux.requestAddBaseDto.formReduxRequestPdInfo[index]
                ? props.addinfo.formRedux.requestAddBaseDto.formReduxRequestPdInfo[index].startDate
                : {}),
              value: item.startDate,
            }),
          };
        });
      } else {
        requestInsAndAccuDto = {
          ...requestInsAndAccuDto,
          [`requestAddBaseDto.${key}`]: Form.createFormField({
            ...props.addinfo.formRedux.requestAddBaseDto[key],
            value,
          }),
        };
      }
    });

    Object.entries(props.addinfo.empLaborContDto).forEach(([key, value]) => {
      requestInsAndAccuDto = {
        ...requestInsAndAccuDto,
        [`empLaborContDto.${key}`]: Form.createFormField({
          ...props.addinfo.formRedux.empLaborContDto[key],
          value,
        }),
      };
    });

    return requestInsAndAccuDto;
  },
})
class AddEmp extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const addEmpSeleInfo = JSON.parse(window.localStorage.getItem('addEmpSeleInfo'));
    // 获取字典
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['BIZ_INS_TYPE', 'BIZ_ACCU_TYPE', 'PAY_FEES_WAY'],
    }).then(dictCode => {
      // 获取报价单信息
      dispatch({
        type: 'addinfo/fetchQuoInfo',
        payload: { addEmpSeleInfo, dictCode },
      });
    });
  }

  // 更新model数据
  updateModelData = payload => {
    const { dispatch } = this.props;
    dispatch({
      type: 'addinfo/updateModelData',
      payload,
    });
  };

  // 提交判重
  submitRepeat = () => {
    const { form, dispatch } = this.props;
    form.validateFieldsAndScroll({ force: true }, (err, values) => {
      // console.log('表单值', values);
      if (!err) {
        dispatch({
          type: 'addinfo/submitRepeat',
          payload: { ...values, empLaborContDto: {...values.empLaborContDto, electrSignFlag: values.empLaborContDto && values.empLaborContDto.electrSignFlag ? +values.empLaborContDto.electrSignFlag : ''} },
        }).then(response => {
          if (response.warningCode !== 1) {
            if (!response.success && response.data && !response.message) {
              confirm({
                icon: <QuestionCircleOutlined />,
                title: response.data,
                okText: '确定',
                okType: 'primary',
                cancelText: '取消',
                style: { top: 200 },
                onOk: () => {
                  dispatch({ type: 'addinfo/submit' });
                },
                onCancel: () => {},
              });
            } else if (!response.success && response.message) {
              message.warning(response.message || '增员提交：服务端错误！');
            } else {
              dispatch({ type: 'addinfo/submit' });
            }
          }
        });
      }
    });
  };

  render() {
    const { addinfo, dictCode, submitLoading, dispatch } = this.props;
    const {
      addinfo: { requestAddBaseDto: { cityId }, isSocialFlag, pdSetFlag, contSerType,isHasIns },
    } = this.props;
    console.log(cityId,'cityIdcityIdcityIdcityIdcityIdcityId8888888888')
    return (
      <PageHeaderWrapper>
        <Spin tip="Loading..." spinning={submitLoading || false}>
          <Form className={styles.addInfoStyle}>
            <Card>
              <Steps current={1}>
                <Step title="选择报价单" />
                <Step title="填写基本信息" />
                <Step title="完成" />
              </Steps>
            </Card>
            <Affix offsetTop={0}>
              <Anchor onClick={e => e.preventDefault()} targetOffset={50}>
                <Row>
                  <Col span={3}>
                    <Link
                      href="/customservicemanage/addemployee/addinfo#basicinfo"
                      title="基本信息"
                    />
                  </Col>
                  <Col span={4}>
                    <Link
                      href="/customservicemanage/addemployee/addinfo#chargeinfo"
                      title="收费信息"
                    />
                  </Col>
                  {addinfo.isHasIns || addinfo.isHasAccu ? (
                    <Col span={3}>
                      <Link
                        href="/customservicemanage/addemployee/addinfo#insaccuinfo"
                        title="社保公积金信息"
                      />
                    </Col>
                  ) : null}
                  {/* {Number(addinfo.contSerType) !== 1 ? (
                    <Col span={3}>
                      <Link
                        href="/customservicemanage/addemployee/addinfo#continfo"
                        title="合同信息"
                      />
                    </Col>
                  ) : null} */}
                  {/* {cityId&&+cityId.value===752252&&Number(addinfo.contSerType) === 1||Number(addinfo.contSerType) !== 1?( */}
                  {cityId && contSerType === 1 && +cityId.value === 752252 && pdSetFlag && +pdSetFlag === 2&&isHasIns ||
                  cityId && contSerType === 1 && +cityId.value === 752252  && pdSetFlag && +pdSetFlag === 1 && isSocialFlag&&isHasIns ||+contSerType !== 1?(
                    <Col span={3}>
                      <Link
                        href="/customservicemanage/addemployee/addinfo#continfo"
                        title="合同信息"
                      />
                    </Col>
                   ) : null}
                  {/* ) : null}  */}
                </Row>
              </Anchor>
            </Affix>
            <Card title={<span style={{ fontWeight: 'bolder' }}>基本信息</span>} id="basicinfo">
              <BasicInfo {...this.props} />
            </Card>
            <Card title={<span style={{ fontWeight: 'bolder' }}>收费信息</span>} id="chargeinfo">
              <ChargeInfo
                {...this.props}
                updateModelData={this.updateModelData}
                dictCode={dictCode}
              />
            </Card>
            <div id="insaccuinfo">
              <InsAccuInfo
                {...this.props}
                dictCode={dictCode}
                updateModelData={this.updateModelData}
              />
            </div>
            {/* {Number(addinfo.contSerType) !== 1 && (
              <Card title={<span style={{ fontWeight: 'bolder' }}>合同信息</span>} id="continfo">
                <ContInfo {...this.props} />
              </Card>
            )} */}
            {}
            {/* addinfo.requestAddBaseDto&&addinfo.requestAddBaseDto.cityId&&addinfo.requestAddBaseDto.cityId==='752252' */}
            {/* {+cityId.value===752252&&Number(addinfo.contSerType) === 1||Number(addinfo.contSerType) !== 1?( */}
            { cityId && contSerType === 1 && +cityId.value === 752252 && pdSetFlag && +pdSetFlag === 2 &&isHasIns||
            cityId && contSerType === 1 && +cityId.value === 752252  && pdSetFlag && +pdSetFlag === 1 && isSocialFlag &&isHasIns||+contSerType !== 1?(
              <Card title={<span style={{ fontWeight: 'bolder' }}>合同信息</span>} id="continfo">
                <ContInfo {...this.props} />
              </Card>
            ) : null}
            {/* ):'null'}  */}
            
            <Card style={{ marginBottom: 30, textAlign: 'center' }} bordered={false}>
              <Button
                style={{ marginRight: 30 }}
                onClick={() => {
                  dispatch({
                    type: 'addinfo/updateModelData',
                    payload: {
                      isGoBack: true,
                    },
                  });
                  router.push('/customservicemanage/addemployee/add');
                }}
              >
                上一步
              </Button>
              <Button type="primary" onClick={this.submitRepeat}>
                下一步
              </Button>
            </Card>
          </Form>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default AddEmp;
